package com.dailyblue.java.spring.boot.redis.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/zset")
@Slf4j
public class ZSetController {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @GetMapping("/a")
    public String a() {
        ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
        zset.add("A", "aa", 9.8);
        zset.add("A", "bb", 5.7);
        zset.add("A", "cc", 1.5);
        zset.add("A", "dd", 11);
        zset.add("A", "ee", 2);
        zset.add("A", "bb", 2);
        zset.addIfAbsent("A", "ff", 4.7);
        zset.addIfAbsent("A", "cc", 4.23);
        Set<String> set1 = Set.of("aa", "bb", "cc", "dd", "ee", "ff");
        Set<String> set2 = Set.of("aa", "mm", "33", "cc", "ff", "kk");
        for (String s : set1) {
            zset.add("B", s, Math.random() * 100);
        }
        for (String s : set2) {
            zset.add("C", s, Math.random() * 100);
        }

        return "";
    }

    @GetMapping("/b")
    public String b() {
        ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
        Set<String> set1 = zset.range("A", 0, -1);
        Long size = zset.count("A", 3, 7);
        String v1 = zset.randomMember("A");
        List<String> set2 = zset.randomMembers("A", 3);
        Set<String> set3 = zset.distinctRandomMembers("A", 3);
        log.info("所有数据：{}", set1);
        log.info("范围个数：{}", size);
        log.info("随机取一个：{}", v1);
        log.info("随机取一群：{}", set2);
        log.info("不重复随机取一群：{}", set3);
        return "";
    }

    @GetMapping("/c")
    public String c() {
        ZSetOperations<String, String> zset = stringRedisTemplate.opsForZSet();
        Set<String> set1 = zset.difference("B", "C");
        Set<String> set2 = zset.union("B", "C");
        Set<String> set3 = zset.intersect("B", "C");
        log.info("set1:{}", set1);
        log.info("set2:{}", set2);
        log.info("set3:{}", set3);

        return "";
    }
}
